package ChatNI;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

import Controller.User;
import Signals.FileMessage;

public class TCPSender extends Thread{

	private FileMessage filemsg;
	private List<User> dest;
	private Socket sock;
	private ChatNI ni;
	private File file;
	private User u; // utilisateur à qui on envoit le msg actuel

	/**
	 * Set the attributes and create the FileMessage
	 * @param file The file we want to send 
	 * @param dest The list of User to which we want to send the TextMessage
	 * @param u  The User to which we want to send the file at the moment
	 */
	public TCPSender(File file, List<User> dest, ChatNI ni, User u) {
		System.out.println("TCPSender: TCPSender: file message create");
		this.dest = dest;
		this.u = u;
		this.ni = ni;
		this.file= file;
		filemsg = new FileMessage(file.getName(),User.FromUserListToStringList(dest),file.length());
		filemsg.setNickname(ni.getLocalUser().getNameIP());
	}


	public void run() {

		try {

			this.sock = new Socket(u.getIp(),ChatNI.porttcp);
			OutputStream os = this.sock.getOutputStream();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(filemsg);
			os.write(baos.toByteArray());

			FileInputStream fis=new FileInputStream(file);             
			byte buf[] = new byte[(int) filemsg.getFileSize()];
			fis.read(buf);
			os.write(buf);

			fis.close();
			oos.close();    

			sock.close();
			//this.interrupt();

		} catch (Exception e) {
			System.out.println("In TCPSender : Could not reach remote host");
			ni.processFileError(filemsg.getNamefile(), dest);
		}


	}

}
